package com.cya.forumproject.controller;

import com.cya.forumproject.common.AppResult;
import com.cya.forumproject.common.ResultCode;
import com.cya.forumproject.config.AppConfig;
import com.cya.forumproject.model.Article;
import com.cya.forumproject.model.Board;
import com.cya.forumproject.model.User;
import com.cya.forumproject.services.IArticleService;
import com.cya.forumproject.services.IBoradService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/9/22 10:15
 * @description：
 * @modified By：
 * @version:
 */
@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;
@Resource
private IBoradService boradService;



    /**
     * 发布新帖子
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @ApiOperation("发布新帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块id")@RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("标题")@RequestParam("title") @NonNull String title ,
                            @ApiParam("内容") @RequestParam("content")@NonNull String content){
        //校验用户禁言状态
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState()==1){
            //用户已经禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);

        }
        //板块校验
        Board board = boradService.selectById(boardId.longValue());
        if (board==null||board.getDeleteState()==1||board.getState()==1){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_BANNED);
        }
        //封装文章对象
        Article article=new Article();
        article.setTitle(title);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setContent(content);
        articleService.creat(article);

        return AppResult.success();

    }
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id")@RequestParam(value = "boardId" ,required = false) Long boardId){
        //定义返回的集合
        List<Article> articles;
        if (boardId==null){
            articles = articleService.selectAll();
        }
        else {
             articles = articleService.selectAllByBoardId(boardId);
        }

        if(articles==null)
        {
          articles=new ArrayList<>();
        }
        return AppResult.success(articles);

    }
    @ApiOperation("根据帖子id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(@ApiParam("帖子id") @RequestParam("id")@NonNull Long id,
                                         HttpServletRequest request){
//        从session获取登录用户的信息
HttpSession session=request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailById(id);
//        判断是否为空
        if (article==null){

            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (article.getUserId()==user.getId()){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public  AppResult modify(@ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                             @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("帖子内容") @RequestParam("content") @NonNull String content,HttpServletRequest request){
//        获取用户信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
//        校验用户状态
        if (user.getState()==1){//1为禁言状态

//          返回错误
return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

//        判断用户是不是文章作者
//        用帖子id查询用户
        Article article = articleService.selectById(id);
        if (article==null){
            return AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
//        用户不是作者
        if (article.getUserId()!=user.getId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
//        判断帖子状态-已归档
        if (article.getState()==1||article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用service
        articleService.modify(id,title,content);
        log.info("帖子更新成功。 Article id="+id+",User id ="+user.getId()+".");

        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUpById")
    public AppResult thumbsUpById(@ApiParam("帖子id")@RequestParam("id")@NonNull Long id ,HttpServletRequest request){
        //检验用户状态
        HttpSession session=request.getSession(false);
       User user= (User) session.getAttribute(AppConfig.USER_SESSION);
       //判断用户是否被禁言
       if (user.getState()==1){
           return AppResult.failed(ResultCode.FAILED_USER_BANNED);
       }

        articleService.thumbsUpById(id);
return AppResult.success();
    }
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(@ApiParam("帖子id")@RequestParam("id")@NonNull Long id ,HttpServletRequest request){

        //检验用户状态
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if (user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
        //判断帖子状态
        if (article==null||article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断是否为作者
        if (article.getUserId()!=user.getId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);


        return AppResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult <List<Article>> getAllByUserId(@ApiParam("用户id")@RequestParam(value = "userId",required = false) Long userId ,HttpServletRequest request ){

        if(userId==null){
            HttpSession session=request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
           userId=user.getId();
        }

        List<Article> articles = articleService.selectByUserId(userId);

        return AppResult.success(articles);


    }

}